package bblrtc

import (
	"fmt"
	"net"
)

type IMGatewayServer struct {
	http_server *HttpServer
	router      *Router
	NodeId      string
	MaxMemory   int64
}

func (s *IMGatewayServer) ListenAndServe() error {
	s.router = new_router(s)
	s.NodeId = GetString("main", "node_id", "abcd")
	s.MaxMemory = int64(GetInt("main", "max_memory", 33554432))

	ll, e := net.Listen("tcp", GetString("main", "listen", ":8780"))
	if e != nil {
		syslog.Println(e)
		panic(e)
	}
	s.http_server = &HttpServer{listener: ll, router: s.router, NodeId: s.NodeId}
	return s.http_server.ListenAndServe()
}

func isTimeout(err error) bool {
	e, ok := err.(net.Error)
	return ok && e.Timeout()
}

const (
	RTC_OFFER     = "RTC-OFFER"
	RTC_CANDIDATE = "RTC-CANDIDATE"
	RTC_ANSWER    = "RTC-ANSWER"
	RTC_BYE       = "RTC-BYE"
)

type Message struct {
	DeviceId  string `json:"devid,omitempty"`
	NodeId    string `json:"node,omitempty"`
	MsgId     string `json:"msgid,omitempty"`
	Mtype     string `json:"type,omitempty"`
	From      string `json:"from,omitempty"`
	To        string `json:"to,omitempty"`
	CallerSID string `json:"caller-sid,omitempty"`
	Text      string `json:"text,omitempty"`
}

func (m *Message) String() string {
	return fmt.Sprintf("DeviceId%v,NodeId:%v,MsgId:%v,CSID:%v,Type:%v,From:%v,To:%v,Text:%v",
		m.DeviceId,
		m.NodeId,
		m.MsgId,
		m.CallerSID,
		m.Mtype,
		m.From,
		m.To,
		m.Text,
	)
}
